﻿package GFlash
{
	import flash.display.MovieClip;
	import flash.events.*;
	import flash.media.Video;
	import flash.net.NetConnection;
	import flash.net.NetStream;
	import flash.display.Stage;

	public class GVideo extends MovieClip
	{
		private var gMainStage:Stage;

		private var gNetConnection:NetConnection;
		private var gNetStream:NetStream;
		private var gVideo:Video;
		private var gVideoClient:Object = new Object();

		private var gVideoPath:String = "";
		private var gAutoPlay:Boolean = false;
		private var gNeedLoop:Boolean = false;
		private var gIsPlaying:Boolean = false;
		private var gTime:Number = 0.0;//s
		private var gPauseTime:Number = 0.0;

		public function GVideo(path:String,MainStage:Stage,Width:int,Height:int,AutoPlay:Boolean=true,NeedLoop:Boolean=false)
		{
			gVideoPath = path;
			gMainStage = MainStage;
			gAutoPlay = AutoPlay;
			gNeedLoop = NeedLoop;

			gNetConnection = new NetConnection();
			gNetConnection.connect(null);
			gVideoClient.onMetaData = OnDuration;
			gNetStream = new NetStream(gNetConnection);
			gNetStream.play(path);
			gNetStream.client = gVideoClient;
			gVideo = new Video(Width,Height);
			gVideo.smoothing = true;
			gVideo.attachNetStream(gNetStream);

			gMainStage.addChild(gVideo);

			gVideo.x = 0;
			gVideo.y = 0;

			if (! gAutoPlay)
			{
				gNetStream.pause();
				gPauseTime = gNetStream.time;
			}
			if (gNeedLoop)
			{
				this.addEventListener(Event.ENTER_FRAME,OnUpdate);
			}
			else
			{
				gNetStream.addEventListener(NetStatusEvent.NET_STATUS,OnNetStatusHandler);
			}
			//gVideo.scaleX=(gMainStage.width/(Width*1.0));
			//gVideo.scaleY=(gMainStage.height/(Height*1.0));
		}
		private function OnDuration(durobject:Object):void
		{
			gTime = durobject.duration;
			trace(gTime);
		}
		private function OnUpdate(e:Event)
		{
			if (gIsPlaying)
			{
				if (GetCurrentTime()>=GetTotalTime()-1)
				{
					gNetStream.seek(0.0);
				}
			}
		}
		private function OnNetStatusHandler(e:NetStatusEvent):void
		{
			switch (e.info.code)
			{
				case "NetConnection.Connect.Success" :
					break;
				case "NetStream.Play.StreamNotFound" :
					//trace("Unable to locate video: " + videoURL);
					break;
				case "NetStream.Buffer.Full" :
					break;
				case "NetStream.Play.Stop" :
					//connectStream();
					gNetStream.removeEventListener(NetStatusEvent.NET_STATUS,OnNetStatusHandler);
					RemoveVideo();
					break;
			}
		}
		public function RemoveVideo()
		{
			gMainStage.removeChild(gVideo);
			gNetStream.dispose();
		}
		public function GetTotalTime():Number
		{
			return gTime;
		}
		public function GetCurrentTime():Number
		{
			return gNetStream.time;
		}
		public function Play()
		{
			gNetStream.seek(gPauseTime);
		}
		public function Pause()
		{
			gNetStream.pause();
			gPauseTime = gNetStream.time;
		}
		public function Stop()
		{

		}
		//......class end
	}

}